// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults



/**
 * Writes text to log
 * @param {Object} txt
 */
function write_to_log(txt){
  $("#log").append(txt + "\n");
}

/**
 * Validates working hour inputs
 */
function validate_hours(){
  $("#add-working-hours").submit(function(){
    if (!validate_times()) 
      return false;
    if (!validate_projects()) 
      return false;
  });
}

/**
 * Validates time fields in working hour form
 */
function validate_times(){
  var rows = $(".project").length;
  for (var i = 0; i < rows; i++) {
    var s_hour = $(".start_time[id='hour__start_time_4i']")[i].value;
    var s_minute = $(".start_time[id='hour__start_time_5i']")[i].value;
    var e_hour = $(".end_time[id='hour__end_time_4i']")[i].value;
    var e_minute = $(".end_time[id='hour__end_time_5i']")[i].value;
    
    // Start time can't be greater than end time
    if (e_hour < s_hour) {
      alert("On row " + (i + 1) + " start time can not be greater than end time!");
      return false;
    }
    
    // If hours equals then start minutes can't be greater than end minutes
    else 
      if (e_hour == s_hour && e_minute < s_minute) {
        alert("On row " + (i + 1) + " end minutes can not be smaller than start minutes!");
        return false;
      }
  }
  return true;
}

/**
 * Validates project name field. Check that user has selected any project for
 * working hour
 */
function validate_projects(){
  var rows = $(".project").length;
  // User can add more fields. Validates every input in row
  for (var i = 0; i < rows; i++) {
    if ($(".project")[i].value == "") {
      alert("On row " + (i + 1) + " no project was selected!");
      return false;
    }
  }
  return true;
}

$(function(){

  /**
   * Check comment form
   */
  $('#add_comment').submit(function(){
    if ($("#comment_body").val() == "") {
      alert("Comment can't be empty");
      return false;
    }
  });
  
  // Attach working hour validation event
  validate_hours();
  
  // Disable margin from the left of navigation
  $('#navigation li:first').css('margin', '0');
  $('.tab:first').css('margin-left', '50px');
	
	// Closes the new hour form
	$("#close_new_hour_form").click(function(){
		$("#add-working-hours").slideUp();
	});
	
	// Toggles the new hour form
	$("#show_new_hour_form").click(function(){
		$("#add-working-hours").slideToggle();
	});
  
});
